//
//  BaseViewController.m
//  SuperDancer
//
//  Created by yu on 2017/10/5.
//  Copyright © 2017年 yu. All rights reserved.
//
#import "BaseViewController.h"

#import "SDUser.h"
#import "SDRequestManager.h"
#import "MBProgressHUD.h"
#import "MBProgressHUD+MJ.h"
#import "UserModel.h"

#define kAcountBtnImgNotification @"AcountBtnImgNotification"

@interface BaseViewController ()

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.translucent = NO;
    [self updateHttpHeader];

//账户1
//    self.users.userId = @"1";
//    self.users.token = @"oaMKIwiR-Qi8QBaJZWEoijFlkuSA";
//账户2
//    self.users.userId = @"81516";
//    self.users.token = @"oaMKIwmXVHfP5r03012sOl5mQP3k";
//账户2
//    self.users.userId = @"81692";
//    self.users.token = @"oaMKIwj_Q0edvkSpEvBtwD1Wzw5Y";
//
//    [[[NIMSDK sharedSDK] loginManager] login:self.users.userId token:self.users.token completion:^(NSError * _Nullable error) {
//        PPLog(@"网易云信登录error：%@", error);
//    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification) name:NOTIFICATION_KTUSER_HAS_LOGOUT object:nil];
}

- (void)receiveNotification {
    [self updateHttpHeader];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)setNavBarShadowImageHidden:(BOOL)hidden {
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    if (hidden) {
        [navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
        [navigationBar setShadowImage:[UIImage new]];
    } else {
        [navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
        [navigationBar setShadowImage:nil];
    }
}

- (void)setStatusBarStyle:(UIStatusBarStyle)style
{
    [[UIApplication sharedApplication] setStatusBarStyle:style];
    [self setNeedsStatusBarAppearanceUpdate];
}

- (SDUser *)users
{
    if (_users == nil) {
        _users = [SDUser sharedUser];
    }
    return _users;
}

- (SDRequestManager *)requestManager
{
    if (_requestManager == nil) {
        _requestManager = [[SDRequestManager alloc] init];
    }
    return _requestManager;
}

#pragma mark - MBProgressHUD

- (MBProgressHUD *)hud
{
    if (_hud == nil)
    {
        _hud = [[MBProgressHUD alloc] initWithView:kKeyWindow];
        [kKeyWindow addSubview:_hud];
        _hud.dimBackground = NO;
        _hud.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
        _hud.labelText = NSLocalizedString(@"正在加载", nil);
    }
    return _hud;
}


#pragma mark - Toast -
- (void)toast:(NSString *)text
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.1];
    hud.mode = MBProgressHUDModeText;
    if (text == nil || [text isEqualToString:@""]) {
        hud.labelText = @"网络似乎出了点异常";
    } else {
        hud.labelText = text;
    }
    hud.margin = 10.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1.5];
}

- (void)showLoading
{
    [MBProgressHUD showHUDAddedTo:kKeyWindow animated:YES];
}

- (void)hideLoading
{
    [MBProgressHUD hideAllHUDsForView:kKeyWindow animated:YES];
}

- (void)success:(NSString *)text {
    [MBProgressHUD showSuccess:text toView:kKeyWindow];
}

- (void)failure:(NSString *)text {
    [MBProgressHUD showError:text toView:kKeyWindow];
}


- (void)setDefaultNavigationBar {
    [self setNavigationBarBackgroundImage:nil
                                tintColor:[UIColor whiteColor]
                                textColor:[UIColor blackColor]
                           statusBarStyle:UIStatusBarStyleDefault];
}

- (void)setClearNavigationBar {
    [self setNavigationBarBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]]
                                tintColor:[UIColor clearColor]
                                textColor:[UIColor clearColor]
                           statusBarStyle:UIStatusBarStyleDefault];
}


- (void)setNavigationBarBackgroundImage:(UIImage *)image
                              tintColor:(UIColor *)tintColor
                              textColor:(UIColor *)textColor
                         statusBarStyle:(UIStatusBarStyle)style {
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setBarTintColor:tintColor];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:textColor,NSFontAttributeName:SYSTEM_FONT(18)};
    [UIApplication sharedApplication].statusBarStyle = style;
}

- (void)hideNavigationBar:(BOOL)hidden animated:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:hidden animated:animated];;
}

- (void)setTitleView:(NSString *)imageName {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 72.0f, 18.0f)];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    UIImage *image = IMAGE_NAMED(imageName);
    imageView.image = image;
    self.navigationItem.titleView = imageView;
}

- (void)setLeftImageNamed:(NSString *)name action:(SEL)action {
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.frame = CGRectMake(0, 0, 30, 30);
    UIImage *image = [UIImage imageNamed:name];
    [_leftBtn setImage:image forState:UIControlStateNormal];
    [_leftBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    _leftBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    @weakify(self);
    [_leftBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        @strongify(self);
        if (!action) {
            [self popBackLastController];
        }
    }];
}

- (void)setLeftItemTitle:(NSString *)title action:(SEL)action {
    NSDictionary *attributes = @{NSFontAttributeName: SYSTEM_FONT(15)};
    CGSize size = [title sizeWithAttributes:attributes];
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _leftBtn.frame = CGRectMake(0, 0, size.width <= 10 ? 70 : size.width + 10, 44);
    _leftBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    _leftBtn.titleLabel.font = SYSTEM_FONT(15);
    [_leftBtn setTitleColor:UIColorHex(333333) forState:UIControlStateNormal];
    [_leftBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [_leftBtn setTitle:title forState:UIControlStateNormal];
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -5;
    
    [_leftBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_leftBtn];
    self.navigationItem.leftBarButtonItems = @[negativeSpacer, backItem];
    
}

- (void)dismissViewController {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)popBackLastController {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setRightItemTitle:(NSString *)title action:(SEL)action {
    [self setRightItemTitle:title titleColor:kTextBlackColor action:action];
}

- (void)setRightItemTitle:(NSString *)title titleColor:(UIColor *)color action:(SEL)action {
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    NSDictionary *attributes = @{NSFontAttributeName: SYSTEM_FONT(15)};
    CGSize size = [title sizeWithAttributes:attributes];
    //! 这里需要根据内容大小来调整宽度
    _rightBtn.frame = CGRectMake(0, 0, size.width <= 10 ? 70 : size.width + 10, 44);
    [_rightBtn setTitleColor:color forState:UIControlStateNormal];
    [_rightBtn setTitleColor:[color colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
    [_rightBtn setTitle:title forState:UIControlStateNormal];
    _rightBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    _rightBtn.titleLabel.font = SYSTEM_FONT(15);
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]
                                       initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                       target:nil action:nil];
    negativeSpacer.width = -5;
    
    [_rightBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    self.navigationItem.rightBarButtonItems = @[negativeSpacer, backItem];
    
}

- (void)setRightImageNamed:(NSString *)name action:(SEL)action {
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image2=  [UIImage imageNamed:name];
    _rightBtn.frame =CGRectMake(0, 0, 50, 44);
    _rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 18, 0, -10);
    [_rightBtn setImage:image2 forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBtn];
}

- (void)setRightImageNamed:(NSString *)name title:(NSString *)title action:(SEL)action {
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame = CGRectMake(0, 0, 80, 25);
//    _rightBtn.backgroundColor = [UIColor cyanColor];
    _rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    _rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 7, 0, 0);
    [_rightBtn setTitleColor:kColorHexStr(@"#707070") forState:UIControlStateNormal];
    _rightBtn.titleLabel.font = Font_NAME_SIZE(@"PingFangSC-Medium", 14);
    [_rightBtn setTitle:title forState:UIControlStateNormal];
    [_rightBtn setImage:IMAGE_NAMED(name) forState:UIControlStateNormal];
    [_rightBtn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_rightBtn];
}

- (void)setupRightItems:(NSArray *)images {
    CGFloat margin = 0.0, width = 35.0;
    UIView *container = [UIView new];
    container.origin = CGPointMake(0, 0);
    container.size = CGSizeMake(width*images.count+margin*(images.count-1), width);
    for (int i=0; i<images.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.origin = CGPointMake(margin*i+width*i, 0);
        button.size = CGSizeMake(width, width);
        button.tag = i+1;
        button.imageEdgeInsets = UIEdgeInsetsMake(0, 10, 0, -10);
        [button setImage:IMAGE_NAMED(images[i]) forState:UIControlStateNormal];
        [container addSubview:button];
        [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        if (i==2) {
            [button addSubview:self.badge];
            _badge.hidden = YES;
            _badge.origin = CGPointMake(ceilf(0.9 * button.width), ceilf(0.1*button.height));
        }
    }
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:container];
    self.navigationItem.rightBarButtonItem = item;
}

- (void)click:(UIButton *)sender {
    if (_block) {
        _block(sender.tag);
    }
}

- (void)setItemBadge:(NSInteger)value {
    if (value==0) {
        _badge.hidden = YES;
        return;
    }
    _badge.hidden = NO;
    if (value>=99) {
        value = 99;
    }
    [_rightBtn addSubview:self.badge];
    _badge.origin = CGPointMake(ceilf(0.85 * _rightBtn.width), ceilf(0.1*_rightBtn.height));
    _badge.hidden = NO;
    _badge.text = [NSString stringWithFormat:@"%@",@(value)];
}

- (void)hideItemBadge {
    _badge.hidden = YES;
}

- (void)setTreasureDetailBadge:(NSInteger)value {
    if (value==0) {
        return;
    }
    if (value>=99) {
        value = 99;
    }
    _badge.hidden = NO;
    _badge.text = [NSString stringWithFormat:@"%@",@(value)];
}

- (YYLabel *)badge {
    if (!_badge) {
        _badge = [YYLabel new];
        _badge.size = CGSizeMake(15, 15);
        _badge.font = SYSTEM_FONT(9);
        _badge.textColor = [UIColor whiteColor];
        _badge.textAlignment = NSTextAlignmentCenter;
        _badge.layer.cornerRadius = _badge.height/2.0;
        _badge.backgroundColor = kTextBlackColor;
    }
    return _badge;
}

- (void)setBackItem {
    [self setBackItemAction:nil];
}

- (void)setBackItemAction:(SEL)sel {
    [self setBackItem:@"返回" action:sel];
    
}

- (void)setBackItem:(NSString *)title action:(SEL)sel {
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithTitle:title style:UIBarButtonItemStylePlain target:self action:sel];
    self.navigationItem.backBarButtonItem = backItem;
}

- (void)pushController:(BaseViewController *)controller {
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)hideBottomBarPush:(BaseViewController *)controller {
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

//更新请求header
- (void)updateHttpHeader {
    PPLog(@"User id = %@\n UserToken = %@",self.users.userId, self.users.token);
    [PPNetworkHelper setValue:NSStringFormat(@"%@", self.users.userId) forHTTPHeaderField:@"Userid"];
    [PPNetworkHelper setValue:NSStringFormat(@"%@", self.users.token) forHTTPHeaderField:@"Usertoken"];
    [self updateUserInfo];
}

//更新用户信息
- (void)updateUserInfo {
    [PPNetworkHelper POST:NSStringFormat(@"%@%@", kApiPrefix, kGetUserInfo) parameters:nil success:^(id responseObject) {
        NSLog(@"%@", responseObject);
        NSString *code = NSStringFormat(@"%@", responseObject[@"code"]);
        if ([code isEqualToString:@"0"]) {
            NSDictionary *info = responseObject[@"data"][@"res"];
            UserModel *userModel = [[UserModel alloc] initWithUserInfo:info];
            self.users.nickName = userModel.nick_name;
            self.users.avatarURL = userModel.user_headimg;
            self.users.background = userModel.background;
            self.users.signature = userModel.signature;
            [[NSNotificationCenter defaultCenter] postNotificationName:kAcountBtnImgNotification object:nil];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (NSString *)jsonToString:(id)data {
    if(data == nil) { return nil; }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
